package impl

import (
	"context"
	"database/sql"
	"fmt"
	"pd/conf"
	"pd/modules"
	"pd/modules/rdp_white_ip"

	log "github.com/marmotedu/iam/pkg/log"
)

// 实例是否实现接口的静态检查
var (
	_    rdp_white_ip.Service = (*RwiImpl)(nil)
	impl                      = &RwiImpl{}
)

// allowed_sign的业务实例
type RwiImpl struct {
	db *sql.DB
	l  log.Logger
}

// Deprecated: Use ImplConfig and init 
func NewRwiImpl() *RwiImpl {
	return &RwiImpl{
		db: conf.C().Mysql.GetDB(),
		l:  log.WithName(rdp_white_ip.AppName),
	}
}

func (i *RwiImpl) CreateRdp_white_ip(ctx context.Context, ins *rdp_white_ip.Rdp_white_ip) (
	*rdp_white_ip.Rdp_white_ip, error) {
	// 第一步校验数据合法性
	if ins.Username == "" || ins.Ip == "" {
		return nil, fmt.Errorf("err: username or ip is null")
	}
	// 第二步默认值填充
	ins.InjectDefualt()
	// 第三步，插入数据到数据库中并保存
	if err := i.saveRdp_white_ip(ctx, ins); err != nil {
		i.l.Errorf("%v insert field ,%v", ins.Username, err)
		return nil, err
	}
	i.l.Infof("%v create success", ins.Username)
	return ins, nil
}

func (ar *RwiImpl) ImplConfig() {
	ar.db = conf.C().Mysql.GetDB()
	ar.l = log.WithName(rdp_white_ip.AppName)
}

func (ar *RwiImpl) ImplName() string {
	return rdp_white_ip.AppName
}

func init() {
	modules.RegistryImpls(impl)
}
